import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:video/bean/department.dart';

///  网络结构数据常量类
class CppeApi {
  CppeApi();

  /// 根据指定部门名称获取相应部门
  ///
  /// @param name:部门名称
  /// @returns 部门id
  ///
  static Future<int> getTree(String name) async {
    int resInt = 0;
    var response = await Dio().post(
        "http://192.168.110.157:8081/departments/tree",
        data: {"name": name});
    var result = json.decode(response.toString());
    if (result["retCode"] == "0" && result["retMessage"] == "成功 | Success") {
      VideoItem videoItem = VideoItem.fromJson(result["data"]);
      var children = videoItem.children;
      children.forEach((element) {
        //print(element.name + "测试打印:" + element.id.toString());
      });
      resInt = videoItem.id;
    }
    return resInt;
  }

  ///
  /// 获取全部部门
  /// @returns Future<Department>部门结构数据
  ///
  static Future<Department> getTreeAll() async {
    var response = await Dio()
        .post("http://192.168.110.157:8081/departments/tree", data: {});
    var result = json.decode(response.toString());
    if (result["retCode"] == "0" && result["retMessage"] == "成功 | Success") {
      Department department = Department.fromJson(result["data"]);
      var dd = department.toJson();
      print(dd);
      return department;
    } else {
      return null;
    }
  }
}

class VideoItem {
  int id;
  String coding;
  String name;
  int parentId;
  List<VideoItem> children;

  VideoItem({this.id, this.coding, this.name, this.parentId, this.children});

  VideoItem.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    coding = json['coding'];
    name = json['name'];
    parentId = json['parentId'];
    if (json['children'] != null) {
      children = <VideoItem>[];
      json['children'].forEach((v) {
        children.add(new VideoItem.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['coding'] = this.coding;
    data['name'] = this.name;
    data['parentId'] = this.parentId;
    if (this.children != null) {
      data['children'] = this.children.map((v) => v.toJson()).toList();
    }
    return data;
  }
}
